package com.techysky.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.techysky.entity.DataModule;
import com.techysky.entity.Paper;
import com.techysky.entity.QuesAndChapter;
import com.techysky.entity.Question;
import com.techysky.entity.QuestionModel;
import com.techysky.entity.QuestionPaper;
import com.techysky.entity.User;
import com.techysky.repository.DataModuleRepository;
import com.techysky.repository.PaperRepository;
import com.techysky.service.PaperManagerService;
import com.techysky.service.QuestionPaperService;
import com.techysky.service.QuestionService;
import com.techysky.util.Contant;

import net.sf.jasperreports.engine.JRAbstractExporter;
import net.sf.jasperreports.engine.JRPrintPage;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.base.JRBasePrintPage;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;

@Controller
@RequestMapping("/paperManager")
public class PaperManagerController{
	private static final Log log=LogFactory.getLog(PaperManagerController.class);
	@Resource
	private PaperManagerService paperManagerService;
	@Resource
	private QuestionPaperService questionPaperService;
	@Resource
	private QuestionService questionService;
	@Autowired
	private DataModuleRepository dataModuleRepository;
	@Autowired
	private PaperRepository paperRepository;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@RequiresPermissions("sys:paper:add")
	@RequestMapping("/papers-add")
	public String questionsadd() {
		return "papers-add";
	}
	
	@RequestMapping("/papers-updata")
	public String papersUpdata() {
		return "papers-updata";
	}	
	
	@RequestMapping(value="/savePaper",method=RequestMethod.POST)
	@ResponseBody
	public String saveQuestion(@ModelAttribute("paper") Paper paper,HttpServletRequest request) {
		String getSystemTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); 
		paper.setCreateDate(getSystemTime);
		User user=null!=request.getSession().getAttribute("user")?(User)request.getSession().getAttribute("user"):new User();
		paper.setCreateUser(user.getUserName());
		Map<String, String[]> map=request.getParameterMap();
		String [] aa=map.get("qids[]");
		
		String[]  score1=map.get("totalScore");
		if(!"现场考试".equals(paper.getExamType())){
			float totalScore=(paper.getCheckCount())*(paper.getCheckScore())+(paper.getJudgeCount())*(paper.getJudgeScore())+(paper.getRadioCount())*(paper.getRadioScore())+(paper.getFillCount())*(paper.getFillScore());
			paper.setTotalScore(totalScore);
			paperManagerService.save(paper);
			if(aa!=null&&aa.length>0){
				for (int i = 0; i < aa.length; i++) {
					String[] str=aa[i].split("-");
					Question q=new Question();
					q.setId(str[0]);
					QuestionPaper qp=new QuestionPaper();
					qp.setPaper(paper);
					qp.setQuestion(q);
					qp.setOrderCode(Long.valueOf(str[1]));
					questionPaperService.save(qp);
				}
			}else{
				String [] aa1=map.get("qids");
				String[] str=aa1[0].split("-");
				Question q=new Question();
				q.setId(str[0]);
				QuestionPaper qp=new QuestionPaper();
				qp.setPaper(paper);
				qp.setQuestion(q);
				qp.setOrderCode(Long.valueOf(str[1]));
				questionPaperService.save(qp);
			}
		}else{
			paper.setTotalScore(Float.valueOf(score1[0]));
			paper.setCreateDate(getSystemTime);
			paperManagerService.save(paper);
		}
		
		return "1";
	}
	@RequiresPermissions("sys:paper:paper")
	@RequestMapping("/papers")
	public String papers() {
		return "papers";
	}
	@RequiresPermissions("sys:paper:view")
	@RequestMapping(value = "/findByPage")
	@ResponseBody
	public Object operator(int pageNo, int pageSize,HttpServletRequest request) {
		PageRequest pageable = new PageRequest(pageNo-1, pageSize);
		String search = request.getParameter("search");
		Page<Paper> qs=paperManagerService.findByPage(pageable,search);
		List<Paper> paperlist=qs.getContent();
		for (int i = 0; i <paperlist.size(); i++) {
			if(!paperlist.get(i).getExamRecord().isEmpty()){
				paperlist.get(i).setStatus("0");//被占用
			}else{
				paperlist.get(i).setStatus("1");
			}
		}
		return paperlist;
	}
	
	
	@RequestMapping("/selquestions")
	@ResponseBody
	public List<Question>  selquestions(String code) {
		
		return questionService.findQuestionByCodeAndId(code);
	}
	@RequestMapping("/edit")
	public ModelAndView edit(String id) {
		Paper paper=paperManagerService.findById(id);
		Iterator<QuestionPaper> questionPapers=paper.getQuestionPaper().iterator();
		List<Question> radioList = new ArrayList<>();
		List<Question> checkList = new ArrayList<>();
		List<Question> judeList = new ArrayList<>();
		List<Question> askList = new ArrayList<>();
		while(questionPapers.hasNext()){
			  QuestionPaper questionPaper = questionPapers.next(); 
			  Question q=questionPaper.getQuestion();
			  q.setOrder(Integer.parseInt(String.valueOf(questionPaper.getOrderCode())));
			  if((Contant.RADIO).equals(q.getCode())){
				  radioList.add(q);
			  }
			  if((Contant.CHECK).equals(q.getCode())){
				  checkList.add(q);
			  }
			  if((Contant.ASK).equals(q.getCode())){
				  askList.add(q);
			  }
			  if((Contant.JUDGE).equals(q.getCode())){
				  judeList.add(q);
			  }
		}
		 Comparator<Question> comparator = (Question o1, Question o2)->{
			 if(ObjectUtils.isEmpty(o1.getOrder())){
				 o1.setOrder(0);
			 }
			 if(ObjectUtils.isEmpty(o2.getOrder())){
				 o2.setOrder(0);
			 }
			 return o1.getOrder()-o2.getOrder();
			 };
		Collections.sort(radioList,comparator);
		Collections.sort(askList,comparator);
		Collections.sort(checkList,comparator);
		Collections.sort(judeList,comparator);
		ModelAndView mv=new ModelAndView();
		mv.setViewName("papers-edit");
		mv.addObject("paper", paper);
		mv.addObject("radioList", radioList);
		mv.addObject("checkList", checkList);
		mv.addObject("askList", askList);
		mv.addObject("judeList", judeList);
		return mv;
	}
	
	@RequestMapping(value="/updatePaper",method=RequestMethod.POST)
	@ResponseBody
	public  String updateQuestion(@ModelAttribute("paper") Paper paper,HttpServletRequest request) {
		Map<String, String[]> map=request.getParameterMap();
		String [] aa=map.get("qids[]");
		String[]  score1=map.get("totalScore");
		if(!"现场考试".equals(paper.getExamType())){
			float totalScore=(paper.getCheckCount())*(paper.getCheckScore())+(paper.getJudgeCount())*(paper.getJudgeScore())+(paper.getRadioCount())*(paper.getFillScore())+(paper.getFillCount())*(paper.getRadioScore());
			paper.setTotalScore(totalScore);
			String getSystemTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); 
			paper.setCreateDate(getSystemTime);
			paperManagerService.save(paper);
			List<QuestionPaper> qps=questionPaperService.findByPaperId(paper.getId());
			String ids="";
			for(int q=0;q<qps.size();q++){
				ids+=qps.get(q).getId()+",";
			}
			if(ids!=""){
				questionPaperService.deleteAll(ids);
			}
			if(aa!=null&&aa.length>0){
				for (int i = 0; i < aa.length; i++) {
					String[] str=aa[i].split("-");
					Question q=new Question();
					q.setId(str[0]);
					QuestionPaper qp=new QuestionPaper();
					qp.setPaper(paper);
					qp.setQuestion(q);
					qp.setOrderCode(Long.valueOf(str[1]));
					questionPaperService.save(qp);
				}
			}else{
				String [] aa1=map.get("qids");
				String[] str=aa1[0].split("-");
				Question q=new Question();
				q.setId(str[0]);
				QuestionPaper qp=new QuestionPaper();
				qp.setPaper(paper);
				qp.setQuestion(q);
				qp.setOrderCode(Long.valueOf(str[1]));
				questionPaperService.save(qp);
			}
			
		}else{
			paper.setTotalScore(Float.valueOf(score1[0]));
			String getSystemTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); 
			paper.setCreateDate(getSystemTime);
			paperManagerService.save(paper);
		}		
		
		return "1";
	}
	@RequestMapping(value="/deletePaper")
	@ResponseBody
	public  String deletePaper(String ids) throws IOException {
        return paperManagerService.deletePapers(ids);
	}
	@RequestMapping(value="/outPapers")
	@ResponseBody
	public  String outPapers(String pids,String paperName){
		String resultStr = "";
		try {
			resultStr= paperManagerService.findPaperByIds(pids,paperName);
		} catch (IOException e) {
			log.info(e);
		}
		 return resultStr;
	}
		@SuppressWarnings({ "unchecked", "rawtypes" })
		@RequestMapping("/export")
		public ResponseEntity<byte[]> exportWord(HttpServletRequest request) {
			
			try {
				//获取参数信息
				URL url = new URL(getReportPath(request)+Contant.TEMPLATE+"/Paper.jasper"); 
				URLConnection conn = url.openConnection();  
				Map<String, Object> params =new HashMap<>();
				params.put("pcode", request.getParameter("pids"));
				ByteArrayOutputStream oStream = new ByteArrayOutputStream();
					JasperPrint jasperPrint = JasperFillManager.fillReport(conn.getInputStream(), params,jdbcTemplate.getDataSource().getConnection());
					JRPrintPage jrpp=new JRBasePrintPage();
					jasperPrint.addPage(jrpp);
					//获取所要导出的是哪种格式文件
					JRAbstractExporter exporter=new JRDocxExporter();
					exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(oStream));
					exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
					exporter.exportReport();
					HttpHeaders headers = new HttpHeaders();
			        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			        String paperName=request.getParameter("paperName");
			        String pname = URLDecoder.decode(paperName,"utf-8"); //对得到的参数进行解码
			        headers.setContentDispositionFormData("attachment", pname+".docx");
			        return new ResponseEntity<>(oStream.toByteArray(),headers, HttpStatus.CREATED);
			                                          
			} catch (Exception e) {
				log.info(e);
			}
			return new ResponseEntity<>(HttpStatus.OK);
		}

		/**
		 * 获取报告路径
		 * @return
		 */
		public String getReportPath(HttpServletRequest request){
			return  request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
		}
		

	 
	 
	@RequestMapping(value="/importPapers",method=RequestMethod.POST)
	@ResponseBody
	public  String importPapers(MultipartFile file){
		File f = new File(file.getOriginalFilename());
		try { 
			file.transferTo(f);
			paperManagerService.txt2String(f);
		}catch (IOException e) {
			log.info(e);
		}
		return "1";
		
	}
	/**
	 * 验证考试名称唯一性
	 * 
	 */	
	@RequestMapping(value = "/paperNameCheck")
	@ResponseBody
	public Object  paperNameCheck(String t_papersname) {
		List<Paper> paperSize =  paperRepository.findByName(t_papersname);
		return paperSize;
	}
	/**
	 * 试卷预览
	 * @param id（试卷id）
	 * @return
	 */
	@RequestMapping("/preview")
	public ModelAndView preview(String id) {
		Paper paper=paperManagerService.findById(id);
		Iterator<QuestionPaper> questionPapers=paper.getQuestionPaper().iterator();
		List<QuesAndChapter> radioList = new ArrayList<>();
		List<QuesAndChapter> checkList = new ArrayList<>();
		List<QuesAndChapter> judeList = new ArrayList<>();
		List<QuesAndChapter> askList = new ArrayList<>();
		List<QuesAndChapter> fillList = new ArrayList<>();
		while(questionPapers.hasNext()){
			  QuestionPaper questionPaper = questionPapers.next(); 
			  Question q=questionPaper.getQuestion();
			  q.setOrder(Integer.parseInt(String.valueOf(questionPaper.getOrderCode())));
			   List<QuestionModel> qms=questionService.findModelByQuestionId(q.getId());
			  qs(radioList, checkList, judeList, askList,fillList, q, qms);
		}
		//################list 集合排序#######################
		 Comparator<QuesAndChapter> comparator = (QuesAndChapter o1, QuesAndChapter o2)->{
			 if(ObjectUtils.isEmpty(o1.getQuestion().getOrder())){
				 o1.getQuestion().setOrder(0);
			 }
			 if(ObjectUtils.isEmpty(o2.getQuestion().getOrder())){
				 o2.getQuestion().setOrder(0);
			 }
			 return o1.getQuestion().getOrder()-o2.getQuestion().getOrder();
			};
		Collections.sort(radioList,comparator);
		Collections.sort(askList, comparator);
		Collections.sort(checkList,comparator);
		Collections.sort(judeList,comparator);
		Collections.sort(fillList,comparator);
		//################list 集合排序#######################
		ModelAndView mv=new ModelAndView();
		mv.setViewName("papers-preview");
		mv.addObject("paper", paper);
		mv.addObject("radioList", radioList);
		mv.addObject("checkList", checkList);
		mv.addObject("askList", askList);
		mv.addObject("judeList", judeList);
		mv.addObject("fillList", fillList);
		return mv;
	}

	private void qs(List<QuesAndChapter> radioList, List<QuesAndChapter> checkList, List<QuesAndChapter> judeList,
			List<QuesAndChapter> askList, List<QuesAndChapter> fillList, Question q, List<QuestionModel> qms) {
		if((Contant.RADIO).equals(q.getCode())){
			  QuesAndChapter quesAndChapter=new QuesAndChapter();
			  quesAndChapter.setQuestion(q);
			  List<DataModule> datamoduleList=new ArrayList<>();
				for(int i=0;i<qms.size();i++){
					//查询章节
					DataModule dm = this.dataModuleRepository.findByDmCode(qms.get(i).getModelDmCode());							
					datamoduleList.add(dm);
				}
				quesAndChapter.setChapterList(datamoduleList);
			  radioList.add(quesAndChapter);
		  }
		  if((Contant.CHECK).equals(q.getCode())){
			  QuesAndChapter quesAndChapter=new QuesAndChapter();
			  quesAndChapter.setQuestion(q);
			  List<DataModule> datamoduleList=new ArrayList<>();
				for(int i=0;i<qms.size();i++){
					//查询章节
					DataModule dm = this.dataModuleRepository.findByDmCode(qms.get(i).getModelDmCode());							
					datamoduleList.add(dm);
				}
				quesAndChapter.setChapterList(datamoduleList);
			  checkList.add(quesAndChapter);
		  }
		  if((Contant.ASK).equals(q.getCode())){
			  QuesAndChapter quesAndChapter=new QuesAndChapter();
			  quesAndChapter.setQuestion(q);
			  	List<DataModule> datamoduleList=new ArrayList<>();
				for(int i=0;i<qms.size();i++){
					DataModule dm = this.dataModuleRepository.findByDmCode(qms.get(i).getModelDmCode());						
					datamoduleList.add(dm);
				}
				quesAndChapter.setChapterList(datamoduleList);
			  askList.add(quesAndChapter);
		  }
		  if((Contant.FILL).equals(q.getCode())){
			  QuesAndChapter quesAndChapter=new QuesAndChapter();
			  quesAndChapter.setQuestion(q);
			  	List<DataModule> datamoduleList=new ArrayList<>();
				for(int i=0;i<qms.size();i++){
					DataModule dm = this.dataModuleRepository.findByDmCode(qms.get(i).getModelDmCode());						
					datamoduleList.add(dm);
				}
				quesAndChapter.setChapterList(datamoduleList);
			  fillList.add(quesAndChapter);
		  }
		  if((Contant.JUDGE).equals(q.getCode())){
			  QuesAndChapter quesAndChapter=new QuesAndChapter();
			  quesAndChapter.setQuestion(q);
			  List<DataModule> datamoduleList=new ArrayList<>();
				for(int i=0;i<qms.size();i++){
					//查询章节
					DataModule dm = this.dataModuleRepository.findByDmCode(qms.get(i).getModelDmCode());						
					datamoduleList.add(dm);
				}
				quesAndChapter.setChapterList(datamoduleList);
			  judeList.add(quesAndChapter);
		  }
	}
   

}
